from enum import Enum

from selenium import webdriver

import Lib
from Lib.zcm.common.element_function import ElementFunction
from Lib.zcm.react.antd.menu import Menu as AntdMenu

from ..common.ui.WaitPageLoad import *
import sys
import inspect
from ..assistant import FwVariables
from .portallogin import portal_login, get_login_info
from .VersionEnum import VersionEnum
# TODO动态加载Page层，Lib层目前固定
import importlib
from ..utils import parse_locator_str

importlib.import_module('Page')
__all__ = ['Common']
modulesList = list(sys.modules.keys())
page_module = sys.modules['Page']


V8_LOGIN = {
    "USER": "inputUserName",
    "PASS": "inputPasswd",
    "BTN": "btnLogin"
}

V9_LOGIN = {
    "USER": "loginUserCode",
    "PASS": "loginPassword",
    "BTN": "btn-login"
}


class Common:
    '''
    Common 类 基础的公共类
    设置
    '''

    _SYSTEM_MENU_LEVEL_V9 = {
        0: "//li[contains(@class,\'js-first-level-menu-list\')]/a/span/span[@title=\'{0}\']/parent::*/parent::*",
        1: "//li[contains(@class,\'js-second-level-menu-list\')]/a/span/span[@title=\'{0}\']/parent::*/parent::*",
        2: "//li[contains(@class,\'js-third-level-menu-list\')]/a/span/span[@title=\'{0}\']/parent::*/parent::*"
    }

    _SYSTEM_MENU_LEVEL_V8 = {
        0: "//li[contains(@class,\'js-first-level-menu-list\')]/a/span/span[@title=\'{0}\']",
        1: "//li[contains(@class,\'js-second-level-menu-list\')]/a/span/span[@title=\'{0}\']",
        2: "//li[contains(@class,\'js-third-level-menu-list\')]/a/span/span[@title=\'{0}\']",
        3: "//li[contains(@class,\'js-forth-level-menu-list\')]/a/span/span[@title=\'{0}\']"
    }

    _SYSTEM_MENU_LEVEL_V9T = {
        0: "//li[contains(@class,\'js-system-level-menu-list\')]/a/span/span[@title=\'{0}\']",
        1: "//li[contains(@class,\'js-first-level-menu-list\')]/a/span/span[@title=\'{0}\']",
        2: "//li[contains(@class,\'js-second-level-menu-list\')]/a/span/span[@title=\'{0}\']",
        3: "//li[contains(@class,\'js-third-level-menu-list\')]/a/span/span[@title=\'{0}\']",
        4: "//li[contains(@class,\'js-forth-level-menu-list\')]/a/span/span[@title=\'{0}\']"
    }

    _SYSTEM_MENU_LEVEL_V9B = {
        0: "//li[contains(@class,\'js-first-level-menu-list\')]//span[@title=\'{0}\']",
        1: "//span[@class='second-menu-title'][@title='{0}']",
        2: "//li[contains(@class,\'ng-item js-menu-item js-menu-listen\')]//span[text()=\'{0}\']"
    }

    _SYSTEM_MENU_LEVEL_V90E = {
        0: "//li[contains(@class,\'js-first-level-menu-list\')]//span[@title=\'{0}\']",
        1: "//span[@class='second-menu-title'][@title='{0}']",
        2: "//li[contains(@class,\'ng-item js-menu-item js-menu-listen\')]//span[@title=\'{0}\']"
    }

    _ALL_MENU = {
        0: "//*[@id='allMenuShowByLetter']/a",
        1: "//li[contains(@class,\'ng-item js-menu-item js-menu-listen\')]/a/span[@title=\'{0}\']"
    }

    _CHECK_MENU_INFO = {
        VersionEnum.ZCM_TEST.version: {
            0: "//li[contains(@class,\'js-first-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            1: "//li[contains(@class,\'js-second-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            2: "//li[contains(@class,\'js-third-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            3: "//li[contains(@class,\'js-forth-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            "VERSION_SYSTEM": "_SYSTEM_MENU_LEVEL_V8",
            "THIRD_HIDDEN_ELE": "//div[contains(@class,\'js-third-level-menu\') and not(contains(@class,\'hidden\'))]",
            "FOUTH_HIDDEN_ELE": "//div[contains(@class,\'js-forth-level-menu\') and not(contains(@class,\'hidden\'))]"
        },
        VersionEnum.ZCM.version: {
            0: "//li[contains(@class,\'js-first-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            1: "//li[contains(@class,\'js-second-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            2: "//li[contains(@class,\'js-third-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            3: "//li[contains(@class,\'js-forth-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            "VERSION_SYSTEM": "_SYSTEM_MENU_LEVEL_V8",
            "THIRD_HIDDEN_ELE": "//div[contains(@class,\'js-third-level-menu\') and not(contains(@class,\'hidden\'))]",
            "FOUTH_HIDDEN_ELE": "//div[contains(@class,\'js-forth-level-menu\') and not(contains(@class,\'hidden\'))]"
        },
        VersionEnum.V8.version: {
            0: "//li[contains(@class,\'js-first-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            1: "//li[contains(@class,\'js-second-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            2: "//li[contains(@class,\'js-third-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            3: "//li[contains(@class,\'js-forth-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            "VERSION_SYSTEM": "_SYSTEM_MENU_LEVEL_V8",
            "THIRD_HIDDEN_ELE": "//div[contains(@class,\'js-third-level-menu\') and not(contains(@class,\'hidden\'))]",
            "FOUTH_HIDDEN_ELE": "//div[contains(@class,\'js-forth-level-menu\') and not(contains(@class,\'hidden\'))]"
        },
        VersionEnum.V9.version: {
            0: "//li[contains(@class,\'js-first-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            1: "//li[contains(@class,\'js-second-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            2: "//li[contains(@class,\'js-third-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            3: "//li[contains(@class,\'js-forth-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            "VERSION_SYSTEM": "_SYSTEM_MENU_LEVEL_V8",
            "THIRD_HIDDEN_ELE": "//div[contains(@class,\'js-third-level-menu\') and not(contains(@class,\'hidden\'))]",
            "FOUTH_HIDDEN_ELE": "//div[contains(@class,\'js-forth-level-menu\') and not(contains(@class,\'hidden\'))]"
        },
        VersionEnum.V90E.version: {
            0: "//li[contains(@class,\'js-first-level-menu-list\')]//span[@title]",
            1: "//span[@class='second-menu-title'][@title]",
            2: "//li[contains(@class,\'ng-item js-menu-item js-menu-listen\')]//span[@title]",
            3: "//li[contains(@class,\'js-forth-level-menu-list\') and not(contains(@class,\'hidden\'))]/a/span/span[@title]",
            "VERSION_SYSTEM": "_SYSTEM_MENU_LEVEL_V90E",
            "THIRD_HIDDEN_ELE": "//div[contains(@class,\'js-third-level-menu\') and not(contains(@class,\'hidden\'))]",
            "FOUTH_HIDDEN_ELE": "//div[contains(@class,\'js-forth-level-menu\') and not(contains(@class,\'hidden\'))]"
        },
    }

    # 有很多重复的，所以text不使用包含
    _BIG_MENU = '//li[@class="whale-components-global-header-header-nav-navItemBox"]//' \
                'span[@class="whale-components-global-header-header-nav-navItemEllipsis" and text()="{0}"]'

    def __init__(self, vesion=None):
        self.version = vesion if vesion else FwVariables.get_version()
        self.cfg_name = FwVariables.get_cfg_name()
        self.url = FwVariables.get_url()
        self.user = FwVariables.get_env_user()
        self.password = FwVariables.get_env_pwd()

        if self.version == VersionEnum.V8.version:
            self.login_info = V8_LOGIN
        elif self.version == VersionEnum.V9.version:
            self.login_info = V9_LOGIN

    def Init(self):
        options = webdriver.ChromeOptions()
        options.add_argument('lang=en_US')
        browser = webdriver.Chrome(chrome_options=options)
        browser.maximize_window()
        return browser

    @staticmethod
    def get_version(browser):
        v = PageElement(browser, "portal", Selector.ID)._execute_script("return portal.appGlobal.attributes.version")
        if v.startswith("V9"):
            return VersionEnum.V9.version
        elif v.startswith("R8"):
            return VersionEnum.V8.version

    def get_login_info(self, url=None, user=None, password=None) -> dict:
        return get_login_info(url=url, user=user, password=password)

    def login(self, browser, url=None, user=None, password=None, version=None):
        portal_login(browser, url, user, password, version)

    def _single_click_menu(self, browser, menu_xpath):
        with WaitPageLoad(browser):
            PageElement(browser, menu_xpath, Selector.XPATH).click()

    def _single_click_menu_mulity_block(self, browser, menu_xpath):
        with WaitPageLoad(browser, interval=2, times=2):
            PageElement(browser, menu_xpath, Selector.XPATH).click()

    def _single_click_by_selenium(self, browser, menu_xpath):
        # with WaitPageLoad(browser, interval=2, times=2):
        i = 0
        while i < 3:
            try:
                WebDriverWait(browser, FwVariables.get_wait_time_out()).until(
                    EC.visibility_of_element_located(
                        (By.XPATH, menu_xpath))).click()
            except ElementClickInterceptedException as e:
                logger.warn("ElementClickInterceptedException occured, trying again...")
                time.sleep(1)
            else:
                break
            i += 1

    def _single_click_menu_V9(self, browser, menu_xpath):
        logger.debug("click menu {0}".format(menu_xpath))
        PageElement(browser, menu_xpath, Selector.XPATH).click()

    def _single_click_menu_V9T(self, browser, menu_xpath):
        logger.debug("click menu {0}".format(menu_xpath))
        PageElement(browser, menu_xpath, Selector.XPATH).click()

    def __openV9Menu(self, version: VersionEnum, browser, *menus):
        system_menu_level = getattr(self, version.system_menu_level)
        with WaitPageLoad(browser, interval=5, times=2):
            PageElement(browser, 'js-menu', Selector.CLASS_NAME).click()
        level = 0
        if menus[0] == "All":
            for menu in menus:
                PageElement(browser, Common._ALL_MENU[level].format(menu), Selector.XPATH).move_curse()
                self._single_click_menu_mulity_block(browser, Common._ALL_MENU[level].format(menu))
                level = level + 1
            try:
                PageElement(browser, "a[title='{}']".format(menu),
                            selector_type=Selector.CSS_SELECTOR).wait_element_presence(
                    FwVariables.get_wait_time_out())
            except:
                logger.error("Please note that the page is not opened within the timeout threshold")
            else:
                logger.info("Page is opened")
        else:
            if len(menus) == 2:
                PageElement(browser, system_menu_level[0].format(menus[0]),
                            Selector.XPATH).move_curse()
                time.sleep(1)
                self._single_click_by_selenium(browser,
                                               system_menu_level[2].format(menus[1]))
            else:
                for menu in menus:
                    PageElement(browser, system_menu_level[level].format(menu),
                                Selector.XPATH).move_curse()
                    time.sleep(1)
                    self._single_click_by_selenium(browser, system_menu_level[level].format(menu))
                    level = level + 1
            try:
                PageElement(browser, "a[title='{}']".format(menu),
                            selector_type=Selector.CSS_SELECTOR).wait_element_presence(
                    FwVariables.get_wait_time_out())
            except:
                logger.error("Please note that the page is not opened within the timeout threshold")
            else:
                logger.info("Page is opened")

    def openMenu(self, browser, *menus: str) -> None:
        try:
            versionEnum = VersionEnum.get_by_version(self.version)
            if versionEnum in [VersionEnum.V8, VersionEnum.V81E]:
                if versionEnum == VersionEnum.V8:
                    portal_name = menus[0]
                    menus = menus[1:]
                    PageElement(browser, "icon-type", Selector.CLASS_NAME).click()
                    portal_elements = PageElement(browser, ".portal-menu-scrollbar>li> a", Selector.CSS_SELECTOR)._get_web_elements()
                    for item in portal_elements:
                        item_father = PageElement.get_parent_element(item)
                        item_active = item_father.get_attribute("class").find("active")
                        if item.text == portal_name and item_active == -1:
                            with WaitPageLoad(browser, 'tabs-WorkSpace', Selector.ID):
                                PageElement(browser, "//a[text()='" + portal_name + "']", Selector.XPATH).click()
                                break
                with WaitPageLoad(browser):
                    PageElement(browser, 'js-menu', Selector.CLASS_NAME).click()
                level = 0
                if menus[0] == "All":
                    for menu in menus:
                        self._single_click_menu(browser, Common._ALL_MENU[level].format(menu))
                        level = level + 1
                else:
                    for menu in menus:
                        self._single_click_menu(browser, Common._SYSTEM_MENU_LEVEL_V8[level].format(menu))
                        level = level + 1
            elif versionEnum == VersionEnum.V9:
                with WaitPageLoad(browser):
                    PageElement(browser, 'js-all-menu', Selector.CLASS_NAME).click()
                level = 0
                if menus[0] == "All":
                    for menu in menus:
                        PageElement(browser, Common._SYSTEM_MENU_LEVEL_V8[level].format(menu),
                                    Selector.XPATH).move_curse()
                        self._single_click_menu(browser, Common._ALL_MENU[level].format(menu))
                        level = level + 1
                else:
                    for menu in menus:
                        PageElement(browser, Common._SYSTEM_MENU_LEVEL_V8[level].format(menu),
                                    Selector.XPATH).move_curse()
                        self._single_click_menu_V9(browser, Common._SYSTEM_MENU_LEVEL_V9[level].format(menu))
                        level = level + 1
            # v9t页面结构更改
            elif versionEnum == VersionEnum.V9T:
                with WaitPageLoad(browser):
                    PageElement(browser, 'js-all-menu', Selector.CLASS_NAME).click()
                level = 0
                if menus[0] == "All":
                    for menu in menus:
                        PageElement(browser, Common._SYSTEM_MENU_LEVEL_V9T[level].format(menu),
                                    Selector.XPATH).move_curse()
                        self._single_click_menu(browser, Common._ALL_MENU[level].format(menu))
                        level = level + 1
                else:
                    for menu in menus:
                        PageElement(browser, Common._SYSTEM_MENU_LEVEL_V9T[level].format(menu),
                                    Selector.XPATH).move_curse()
                        self._single_click_menu_V9T(browser, Common._SYSTEM_MENU_LEVEL_V9T[level].format(menu))
                        level = level + 1
            elif versionEnum in [VersionEnum.V90E, VersionEnum.V9B]:
                self.__openV9Menu(versionEnum, browser, *menus)
            elif versionEnum == VersionEnum.BIG_DATA:
                # 点击菜单按钮，让菜单出来
                element = PageElement(browser, 'a.whale-components-global-header-header-nav-navBtn', By.CSS_SELECTOR)
                element.wait_element_presence(30)  # 等30秒
                element.click()
                # antd 菜单
                menu = AntdMenu(browser)
                # 第一级菜单是 antd的，后面的菜单不是
                menu.open_menu(menus[0])
                # 尝试打开后面的菜单
                for menu in menus[1:]:
                    self._single_click_menu(browser, Common._BIG_MENU.format(menu))
            elif versionEnum == VersionEnum.TEST:
                menu = AntdMenu(browser)
                menu.open_menu(*menus)

        except Exception as e:
            raise TestException.by_exception(e)

    def screenShot(self, browser, path):
        picture_url = browser.get_screenshot_as_file(path)

    def closeBrowser(self, browser):
        browser.close()

    def quitBrowser(self, browser):
        browser.quit()

    def init_page(self, browser, page):
        logger.debug("init page {0}".format(page))
        module = self._get_page_class(page)
        pageInit = module(browser).init_page(browser)
        return pageInit

    def _get_page_class(self, page: str):
        for name, obj in inspect.getmembers(page_module):
            if inspect.isclass(obj):
                logger.debug("check page {0} {1} {2}".format(obj.__name__, obj.__module__, obj))
                # 重名Page，需要强匹配，增加modul比较
                if '.' in page and obj.__module__ + '.' + obj.__name__ == page:
                    return obj
                elif page == obj.__name__:
                    return obj
        raise TestException.by_error_code(ErrorCode.PAGE_NOT_FIND, value=page)

    def get_element_by_selector(self, browser, locator: str):
        """根据locator找到元素，并且匹配出是什么组件
        """
        # 是不是Page配置
        if locator.upper().startswith('P='):
            from ..assistant.page_config import page_parser
            locator = page_parser.read(locator[2:])

        selector_type, selector = parse_locator_str(locator)
        logger.info("locator parse result: %s, %s" % (selector_type, selector))
        if selector_type:
            element = ElementFunction(browser).try_find_element_in_page(selector, selector_type)
        else:
            # 如果没有指定selector Type
            # 按下面查找顺序尝试去查找
            selector = locator
            selector_types = [By.CLASS_NAME, By.CSS_SELECTOR, By.XPATH, By.ID]
            for selector_type in selector_types:
                element = ElementFunction(browser).try_find_element_in_page(selector, selector_type, 3)
                if element:
                    logger.info("find the element by selector type {0}".format(selector_type))
                    break
        if not element:
            raise TestException.by_error_code(ErrorCode.NOT_LOCATE_ELEMENT, selector_type='Any', selector=locator)

        element_libs = [Lib.zcm.react.antd, Lib.zcm.fish, Lib.zcm.common]
        for element_lib in element_libs:
            for name, obj in inspect.getmembers(element_lib, inspect.isclass):
                functions = inspect.getmembers(obj, inspect.isfunction)
                function_names = [item[0] for item in functions]
                if 'get_identification' in function_names:
                    logger.debug("check element to match {0} {1} {2}".format(name, obj.__module__, obj))
                    element_obj = obj(browser, selector, selector_type)
                    identification = element_obj.get_identification()
                    logger.debug("identification: {0}".format(identification))
                    if identification:
                        for key, value in identification.items():
                            if not self._is_element_match(key, value, element):
                                break
                        else:
                            logger.info("Match the {0} element success".format(name))
                            return element_obj

        # 没有找到, 返回基本的PageElement对像
        logger.info("Not match the element and return default page element")
        return PageElement(browser, selector, selector_type)

    def _is_element_match(self, id_key, id_values, element):
        logger.debug("try to match the {0} attribute".format(id_key))
        if id_key == 'tag':
            element_value = element.tag_name
        else:
            element_value = element.get_attribute(id_key)
        # 如果没有这个属性，则返回False
        if element_value is None:
            logger.debug("the element has not {0} attribute, match filed".format(id_key))
            return False
        element_values = element_value.split()
        for value in element_values:
            if value in id_values:
                logger.debug('the element {0} values has {1}, match success'.format(id_key, value))
                return True
        logger.debug(
            "the element {0} attribute values {1} has not matched identification {2}".format(id_key, element_value,
                                                                                             id_values))
        return False

    def __zcm_click_alert(self, driver):
        if self.version == VersionEnum.ZCM.version:
            selector = '//div[@class="modal-footer"]/button[contains(@class,"current-tab")]'
            element = ElementFunction(driver).try_find_element_in_page(selector)
            if element:
                with WaitPageLoad(driver):
                    # 通过selector 转成组件
                    element = self.get_element_by_selector(driver, selector)
                    element.click()

    def check_menu(self, obj, url, username, password, version=None):
        # 登陆
        time_sleep = 0.2
        obj.login(url, username, password, version=version)
        versionEnum = VersionEnum.get_by_version(self.version)
        if versionEnum == VersionEnum.ZCM_TEST:
            obj.click("//ins[@class='icheck-helper']")
            obj.click("//a[@id='btnLogin']")
        elif versionEnum == VersionEnum.V90E:
            obj.click('//button[contains(@class,"js-ok")]')
        # list_text = []
        portal_menus = PageElement(obj._drivers.current, 'portalDropdown', Selector.ID)
        error_page_info = []
        success_page_info = []
        SYSTEM_MENU_LEVEL_INFO = getattr(self, self._CHECK_MENU_INFO[self.version]["VERSION_SYSTEM"])
        if versionEnum == VersionEnum.V9:
            with WaitPageLoad(obj._drivers.current):
                PageElement(obj._drivers.current, 'js-all-menu', Selector.CLASS_NAME).click()
            time.sleep(0.5)
            menu_text_list = []
            menu_elems = obj._drivers.current.find_elements_by_xpath(self._CHECK_MENU_INFO[self.version][0])
            logger.info(self._CHECK_MENU_INFO[self.version][0])
            logger.info("menu_elems:{}".format(menu_elems))
            for menu_elem in menu_elems:
                title = menu_elem.get_attribute("title")
                menu_text_list.append(title)
            # 一级菜单
            logger.info(menu_text_list)
            portal_menu_parm_info = {VersionEnum.V9.version: []}
            for text in portal_menu_parm_info:
                for menu_text in menu_text_list:
                    # menu_text 用户角色
                    PageElement(obj._drivers.current, SYSTEM_MENU_LEVEL_INFO[0].format(menu_text),
                                Selector.XPATH).move_curse()
                    time.sleep(time_sleep)
                    # 二级菜单
                    second_menu_elems = obj._drivers.current.find_elements_by_xpath(
                        self._CHECK_MENU_INFO[self.version][1])
                    logger.info("second_menu_elems:{}".format(second_menu_elems))
                    logger.info("second_menu_elems长度:{}".format(len(second_menu_elems)))
                    if second_menu_elems:
                        second_menu_text_list = []
                        for second_menu_elem in second_menu_elems:
                            second_menu_text_list.append(second_menu_elem.get_attribute("title"))
                        for second_menu_text in second_menu_text_list:
                            PageElement(obj._drivers.current, SYSTEM_MENU_LEVEL_INFO[1].format(second_menu_text),
                                        Selector.XPATH).move_curse()
                            time.sleep(time_sleep)
                            # 三级菜单
                            # 需判断三级菜单是否hidden
                            third_menu_elems_not_hidden = obj._drivers.current.find_elements_by_xpath(
                                self._CHECK_MENU_INFO[self.version]["THIRD_HIDDEN_ELE"])
                            if third_menu_elems_not_hidden:
                                third_menu_elems = obj._drivers.current.find_elements_by_xpath(
                                    self._CHECK_MENU_INFO[self.version][2])
                                for third_menu_elem in third_menu_elems:
                                    third_menu_text = third_menu_elem.get_attribute("title")
                                    PageElement(obj._drivers.current, SYSTEM_MENU_LEVEL_INFO[2].format(third_menu_text),
                                                Selector.XPATH).move_curse()
                                    time.sleep(time_sleep)
                                    # 需判断四级菜单是否hidden
                                    forth_menu_elems_not_hidden = obj._drivers.current.find_elements_by_xpath(
                                        self._CHECK_MENU_INFO[self.version]["FOUTH_HIDDEN_ELE"])
                                    if forth_menu_elems_not_hidden:
                                        forth_menu_elems = obj._drivers.current.find_elements_by_xpath(
                                            self._CHECK_MENU_INFO[self.version][3])
                                        for forth_menu_elem in forth_menu_elems:
                                            forth_menu_text = forth_menu_elem.get_attribute("title")
                                            url = forth_menu_elem.find_element_by_xpath(
                                                SYSTEM_MENU_LEVEL_INFO[3].format(
                                                    forth_menu_text) + "/../..").get_attribute("menu_url")
                                            logger.info("forth_url:{}".format(url))
                                            portal_menu_parm_info[text].append((menu_text, second_menu_text,
                                                                                third_menu_elem.get_attribute("title"),
                                                                                forth_menu_text, url))
                                    else:
                                        url = third_menu_elem.find_element_by_xpath(
                                            SYSTEM_MENU_LEVEL_INFO[2].format(third_menu_text) + "/../..").get_attribute(
                                            "menu_url")
                                        logger.info("third_url:{}".format(url))
                                        portal_menu_parm_info[text].append(
                                            (menu_text, second_menu_text, third_menu_elem.get_attribute("title"), url))
                            else:
                                url = obj._drivers.current.find_element_by_xpath(
                                    SYSTEM_MENU_LEVEL_INFO[1].format(second_menu_text) + "/../..").get_attribute(
                                    "menu_url")
                                logger.info("second_url:{}".format(url))
                                portal_menu_parm_info[text].append((menu_text, second_menu_text, url))
                    else:
                        # get_attribute("属性")
                        url = obj._drivers.current.find_element_by_xpath(
                            SYSTEM_MENU_LEVEL_INFO[0].format(menu_text) + "/../..").get_attribute("menu_url")
                        logger.info("first_url:{}".format(url))
                        portal_menu_parm_info[text].append((menu_text, url))
                    break
            obj._drivers.current.refresh()
        elif versionEnum == VersionEnum.V90E:
            portal_menus.move_curse()
            elem = obj._drivers.current.find_elements_by_xpath(
                '//ul[contains(@class,"portalMenu")]/li[contains(@class,"portal-menu__item")]/a')
            logger.info("elem:{}".format(elem))
            portal_menu_parm_info = dict()
            for each_ul in elem:
                each_ul_text = each_ul.get_attribute("innerText")
                logger.info("li_text:{}".format(each_ul_text))
                portal_menu_parm_info[each_ul_text] = []
            logger.info("portal_menu_parm_info:{}".format(portal_menu_parm_info))
            for text in portal_menu_parm_info:
                try:
                    obj.change_portal(text)
                except:
                    obj._drivers.current.refresh()
                    obj.change_portal(text)
                self.__zcm_click_alert(obj._drivers.current)
                with WaitPageLoad(obj._drivers.current, interval=5, times=2):
                    PageElement(obj._drivers.current, 'js-menu', Selector.CLASS_NAME).click()
                menu_text_list = []
                menu_elems = obj._drivers.current.find_elements_by_xpath(self._CHECK_MENU_INFO[self.version][0])
                logger.info(self._CHECK_MENU_INFO[self.version][0])
                for menu_elem in menu_elems:
                    title = menu_elem.get_attribute("title")
                    menu_text_list.append(title)
                # 一级菜单
                logger.info("{}:{}".format(text, menu_text_list))
                for menu_text in menu_text_list:
                    # menu_text 用户角色
                    PageElement(obj._drivers.current, SYSTEM_MENU_LEVEL_INFO[0].format(menu_text),
                                Selector.XPATH).move_curse()
                    time.sleep(time_sleep)
                    third_menu_elems = obj._drivers.current.find_elements_by_xpath(
                        self._CHECK_MENU_INFO[self.version][2])
                    if third_menu_elems:
                        for third_menu_elem in third_menu_elems:
                            is_displayed = third_menu_elem.is_displayed()
                            logger.info("is_displayed:{}".format(is_displayed))
                            if is_displayed:
                                third_menu_text = third_menu_elem.get_attribute("title")
                                logger.info("third_menu_text:{}".format(third_menu_text))
                                url = third_menu_elem.find_element_by_xpath(
                                    SYSTEM_MENU_LEVEL_INFO[2].format(third_menu_text) + "/..").get_attribute("url")
                                logger.info("url:{}".format(url))
                                portal_menu_parm_info[text].append(
                                    (menu_text, third_menu_text, url))
                    else:
                        url = obj._drivers.current.find_element_by_xpath(
                            SYSTEM_MENU_LEVEL_INFO[0].format(menu_text) + "/..").get_attribute("url")
                        logger.info("url:{}".format(url))
                        portal_menu_parm_info[text].append((menu_text, url))
        else:
            is_open = portal_menus._get_web_element(True).get_attribute('class')
            if is_open != 'open':
                # 移动鼠标看能不能出来菜单
                portal_menus.move_curse()
                is_open = portal_menus._get_web_element(True).get_attribute('class')
                logger.info("move之后:{}".format(is_open))
            if is_open != 'open':
                # 点击看能不能出来
                portal_menus.click()
            elem = obj._drivers.current.find_elements_by_xpath(
                '//ul[contains(@class,"portalMenu")]/li[contains(@class,"portal-menu__item")]/a')
            logger.info("elem:{}".format(elem))
            portal_menu_parm_info = dict()
            for each_ul in elem:
                each_ul_text = each_ul.get_attribute("innerText")
                logger.info("li_text:{}".format(each_ul_text))
                portal_menu_parm_info[each_ul_text] = []
            logger.info("portal_menu_parm_info:{}".format(portal_menu_parm_info))
            SYSTEM_MENU_LEVEL_INFO = getattr(self, self._CHECK_MENU_INFO[self.version]["VERSION_SYSTEM"])
            for text in portal_menu_parm_info:
                # if text != "Root Portal":
                #     continue
                obj.change_portal(text)
                self.__zcm_click_alert(obj._drivers.current)
                with WaitPageLoad(obj._drivers.current, interval=5, times=2):
                    PageElement(obj._drivers.current, 'js-menu', Selector.CLASS_NAME).click()
                menu_text_list = []
                menu_elems = obj._drivers.current.find_elements_by_xpath(self._CHECK_MENU_INFO[self.version][0])
                logger.info(self._CHECK_MENU_INFO[self.version][0])
                for menu_elem in menu_elems:
                    title = menu_elem.get_attribute("title")
                    menu_text_list.append(title)
                # 一级菜单
                logger.info(menu_text_list)
                for menu_text in menu_text_list:
                    # menu_text 用户角色
                    PageElement(obj._drivers.current, SYSTEM_MENU_LEVEL_INFO[0].format(menu_text),
                                Selector.XPATH).move_curse()
                    time.sleep(time_sleep)
                    # 二级菜单
                    second_menu_elems = obj._drivers.current.find_elements_by_xpath(
                        self._CHECK_MENU_INFO[self.version][1])
                    if second_menu_elems:
                        second_menu_text_list = []
                        for second_menu_elem in second_menu_elems:
                            second_menu_text_list.append(second_menu_elem.get_attribute("title"))
                        for second_menu_text in second_menu_text_list:
                            PageElement(obj._drivers.current, SYSTEM_MENU_LEVEL_INFO[1].format(second_menu_text),
                                        Selector.XPATH).move_curse()
                            time.sleep(time_sleep)
                            # 三级菜单
                            # 需判断三级菜单是否hidden
                            third_menu_elems_not_hidden = obj._drivers.current.find_elements_by_xpath(
                                self._CHECK_MENU_INFO[self.version]["THIRD_HIDDEN_ELE"])
                            if third_menu_elems_not_hidden:
                                third_menu_elems = obj._drivers.current.find_elements_by_xpath(
                                    self._CHECK_MENU_INFO[self.version][2])
                                for third_menu_elem in third_menu_elems:
                                    third_menu_text = third_menu_elem.get_attribute("title")
                                    PageElement(obj._drivers.current, SYSTEM_MENU_LEVEL_INFO[2].format(third_menu_text),
                                                Selector.XPATH).move_curse()
                                    time.sleep(time_sleep)
                                    # 需判断四级菜单是否hidden
                                    forth_menu_elems_not_hidden = obj._drivers.current.find_elements_by_xpath(
                                        self._CHECK_MENU_INFO[self.version]["FOUTH_HIDDEN_ELE"])
                                    if forth_menu_elems_not_hidden:
                                        forth_menu_elems = obj._drivers.current.find_elements_by_xpath(
                                            self._CHECK_MENU_INFO[self.version][3])
                                        for forth_menu_elem in forth_menu_elems:
                                            forth_menu_text = forth_menu_elem.get_attribute("title")
                                            url = forth_menu_elem.find_element_by_xpath(
                                                SYSTEM_MENU_LEVEL_INFO[3].format(
                                                    forth_menu_text) + "/../..").get_attribute("url")
                                            logger.info("url:{}".format(url))
                                            portal_menu_parm_info[text].append((menu_text, second_menu_text,
                                                                                third_menu_elem.get_attribute("title"),
                                                                                forth_menu_text, url))
                                    else:
                                        url = third_menu_elem.find_element_by_xpath(
                                            SYSTEM_MENU_LEVEL_INFO[2].format(third_menu_text) + "/../..").get_attribute(
                                            "url")
                                        logger.info("url:{}".format(url))
                                        portal_menu_parm_info[text].append(
                                            (menu_text, second_menu_text, third_menu_elem.get_attribute("title"), url))
                            else:
                                url = obj._drivers.current.find_element_by_xpath(
                                    SYSTEM_MENU_LEVEL_INFO[1].format(second_menu_text) + "/../..").get_attribute("url")
                                logger.info("url:{}".format(url))
                                portal_menu_parm_info[text].append((menu_text, second_menu_text, url))
                    else:
                        # get_attribute("属性")
                        url = obj._drivers.current.find_element_by_xpath(
                            SYSTEM_MENU_LEVEL_INFO[0].format(menu_text) + "/../..").get_attribute("url")
                        logger.info("url:{}".format(url))
                        portal_menu_parm_info[text].append((menu_text, url))
        logger.info(portal_menu_parm_info)
        for portal_name in portal_menu_parm_info:
            # portal_name = portal_menu_parm[0]
            menu_parms = portal_menu_parm_info[portal_name]
            if versionEnum != VersionEnum.V9:
                try:
                    obj.change_portal(portal_name)
                    self.__zcm_click_alert(obj._drivers.current)
                except Exception as e:
                    logger.error(traceback.format_exc())
                    obj._drivers.current.refresh()
                    obj.change_portal(portal_name)
                    self.__zcm_click_alert(obj._drivers.current)
            for menu_parm_url in menu_parms:
                menu_parm = menu_parm_url[:-1]
                url = menu_parm_url[-1]
                logger.info("portal:{},menu:{},url:{}".format(portal_name, menu_parm, url))
                try:
                    obj.open_menu(*menu_parm)
                    time.sleep(time_sleep)
                    check_page_flag = obj.check_page()
                except Exception as e:
                    logger.error(traceback.format_exc())
                    obj._drivers.current.refresh()
                    obj.open_menu(*menu_parm)
                    time.sleep(time_sleep)
                    check_page_flag = obj.check_page()

                if not check_page_flag:
                    obj.process_fish_modal_dialog_alert()
                    error_page_info.append("\t".join((portal_name,) + (url,) + menu_parm))
                else:
                    success_page_info.append("\t".join((portal_name,) + (url,) + menu_parm))
            # break
        logger.info(
            "\nsuccess_page_info:\nportal\t\turl\t一级菜单\t二级菜单\t三级菜单\t四级菜单\n{}".format("\n".join(success_page_info)))
        logger.info("\nerror_page_info:\nportal\t\turl\t一级菜单\t二级菜单\t三级菜单\t四级菜单\n{}".format("\n").join(error_page_info))
        return success_page_info, error_page_info

        # self.open_menu("All")
